﻿using log4net;
using Mangox.BLL.Mangox;
using Mangox.Common;
using Mangox.Model.Common;
using MGXAPI.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;

namespace MGXAPI.Controllers.API.Mangox
{
    public class ShuiLongTouController : ApiController
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";       //获取类名 
        Random rd = new Random();
        //public static SLTResultModel CountModel = new SLTResultModel();
        public static long userCount = 0;
        public static long touchCount = 0;

        public ShuiLongTouController()
        {
            InitCount();
        }

        /// <summary>
        /// 获取每日空投总数
        /// 用途：根据用户点击量分配。
        /// 空投放在下面一起返回
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetKontTouNum(RequestM_UserModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            result.Code = 0;
            result.Data = "100"; //100万个
            return result;
        }


        /// <summary>
        /// 根据用户获取邀请数
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetInvited(RequestM_UserModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            result.Code = 0;
            result.Data = new { InvitedNum = 102, KontTouNum = 1005 };
            return result;
        }

        /// <summary>
        /// 获取每日点击量，计算出每日奖励列表
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetRewardList(RequestM_UserModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            var bll = new ShuiLongTouBLL();
            var list = bll.GetRewardCountList((int)p.UserID);

            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    //计算每日平均奖励
                    item.DailyReward = 1000000 / item.TouchCount;
                }
            }

            result.Code = 0;
            result.Data = list;
            return result;
        }

        /// <summary>
        /// 水龙头提交保存ERC地址，并创建用户
        /// *创建和登陆在一起；如果已经存在就直接登陆
        /// http://localhost:13772/api/ShuiLongTou/CreateUser
        /// 参数：
        /// {{"Source":"0","LoginName":"xiaoming","Password":"123456","UserName":"小明","MgxHashID":"","ERCAddress":"","Mobile":"18888888888","Email":"123456@outlook.com","Gender":"男"}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel CreateUserSLT(RequestM_UserModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            log.Info(className + $"CreateUserSLT param-{JsonCommon.ToJson(p)}");
            try
            {
                /********** 参数验证 *********/
                if (p == null)
                {
                    result.Msg = "参数为空";
                    return result;
                }

                if (string.IsNullOrWhiteSpace(p.ERCAddress))
                {
                    result.Msg = "ERCAddress不能为空";
                    return result;
                }
                //else if (p.ERCAddress.Length != 64)
                //{
                //    result.Msg = "ERCAddress格式不正确";
                //    return result;
                //}

                MgxUserBLL bll = new MgxUserBLL();
                var sltBLL = new ShuiLongTouBLL();

                //已经存在就直接登陆
                var user = bll.GetUserSlt(p.UserID.ToString(), p.ERCAddress, (int)AppType.ShuiLongTou);
                if (user != null && user.ID > 0)
                {
                    //登陆成功刷新用户
                    userCount = sltBLL.GetUserCount();

                    result.Code = 1;
                    result.Msg = "登陆成功";
                    result.Data = new
                    {
                        UserID = user.UserID,
                        Token = MgxCommBLL.CreateToken(user.UserID.ToString(), ""),
                        UserCount = userCount,
                        TouchCount = touchCount
                    };
                    return result;
                }

                //var cpwd = MgxCommBLL.CheckPassword(p.Password);
                //if (!string.IsNullOrEmpty(cpwd))
                //{
                //    result.Msg = cpwd;
                //    return result;
                //}

                //密码 加密
                p.Password = "123456";  //默认密码
                p.Password = MgxCommBLL.GetUserPwd(p.Password);

                //UserName为空则默认LoginName
                //if (string.IsNullOrEmpty(p.UserName))
                //{
                //    p.UserName = p.LoginName;
                //}


                //创建账号
                p.UserID = bll.CreateUserID();
                if (p.UserID <= 0)
                {
                    result.Msg = "创建账户失败";
                    return result;
                }

                //默认值
                p.AppType = (int)AppType.ShuiLongTou;
                p.State = (int)UserStatus.Enabled;
                p.CreateTime = DateTime.Now;
                p.LoginTime = DateTime.Now;
                p.LastLoginTime = DateTime.Now;
                p.LoginCount = 1;
                p.AppType = (int)AppType.ShuiLongTou;
                if (p.Source == null)
                {
                    p.Source = (int)Source_MGX.weizhi;
                }

                var flag = bll.AddUser(p);
                if (flag)
                {
                    //创建成功
                    userCount = sltBLL.GetUserCount();

                    result.Code = 0;
                    result.Msg = "创建用户成功";
                    result.Data = new
                    {
                        p.UserID,
                        Token = MgxCommBLL.CreateToken(p.UserID.ToString(), ""),
                        UserCount = userCount,
                        TouchCount = touchCount
                    };
                }
                else
                {
                    result.Msg = "创建用户失败";
                }
            }
            catch (Exception ex)
            {
                result.Msg = ex.ToString();
                log.Error(className + $"CreateUserSLT Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 添加空投信息API
        /// http://localhost:13772/api/ShuiLongTou/AddShuiLongTou
        /// 参数：{"Source":"0","Token":"","UserID":"","PxgID":"123","AddressType":"BTC","BTCAddress":"test","ETHAddress":""}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel AddShuiLongTou(ShuiLongTouRqt p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            log.Info(className + $"AddShuiLongTou param-{JsonCommon.ToJson(p)}");
            try
            {
                ShuiLongTouBLL bll = new ShuiLongTouBLL();

                //if (param == null)
                //{
                //    result.Msg = "参数为空";
                //    return result;
                //}

                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }

                #endregion

                p.UserID = token.UserID;
                p.CreateTime = DateTime.Now;
                var flag = bll.AddShuiLongTou(p);
                if (flag)
                {
                    //刷新数据
                    //userCount = bll.GetUserCount(); //在添加用户后刷新
                    touchCount = ++touchCount; //点击后+1

                    result.Code = 0;
                    result.Msg = "保存成功";
                    result.Data = new
                    {
                        Token = MgxCommBLL.CreateToken(p.UserID.ToString(), ""),
                        UserCount = userCount,
                        TouchCount = touchCount
                    };
                }
                else
                {
                    result.Msg = "保存失败";
                }
            }
            catch (Exception ex)
            {
                result.Msg = ex.ToString();
                log.Error(className + $"AddShuiLongTou Fail-{ex.ToString()}");
            }
            return result;
        }

        /// <summary>
        /// 获取点击总数等初始化数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetTouchInit(KongTouModelRqt p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            log.Info(className + $"GetTouchCount param-{JsonCommon.ToJson(p)}");
            try
            {
                var bll = new ShuiLongTouBLL();
                
                result.Code = 0;
                result.Msg = "获取成功";
                result.Data = new
                {
                    UserCount = userCount,
                    TouchCount = touchCount,
                };
                return result;


                //KongTouBLL bll = new KongTouBLL();

                //var flag = bll.AddKongTou(p);
                //if (flag)
                //{
                //    result.Code = 0;
                //    result.Msg = "保存成功";
                //    result.Data = new
                //    {
                //        Token = MgxCommBLL.CreateToken(p.UserID.ToString(), ""),
                //        Count = ++count
                //    };
                //}
                //else
                //{
                //    result.Msg = "保存失败";
                //}
            }
            catch (Exception ex)
            {
                result.Msg = ex.ToString();
                log.Error(className + $"GetTouchCount Fail-{ex.ToString()}");
            }
            return result;
        }

        private void InitCount()
        {
            if (userCount == 0 || touchCount == 0)
            {
                var bll = new ShuiLongTouBLL();
                userCount = bll.GetUserCount();
                touchCount = bll.GetTouchCount();
            }
        }



    }
}
